import router from "@/router"
import { useUserStoreHook } from "@/store/modules/user"
import { usePermissionStoreHook } from "@/store/modules/permission"
import { ElMessage } from "element-plus"
import { setRouteChange } from "@/hooks/useRouteListener"
import { useTitle } from "@/hooks/useTitle"
import { getToken } from "@/utils/cache/cookies"
import routeSettings from "@/config/route"
import { buildTree } from '@/utils'
import isWhiteList from "@/config/white-list"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
const { setTitle } = useTitle()
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, _from, next) => {
  NProgress.start()
  const userStore = useUserStoreHook()
  const permissionStore = usePermissionStoreHook()

  const token = getToken()
  // 如果没有登陆
  if (!token) {
    // 如果在免登录的白名单中，则直接进入
    if (isWhiteList(to)) return next()
    // 其他没有访问权限的页面将被重定向到登录页面
    return next("/login")
  }

  // 如果已经登录，并准备进入 Login 页面，则重定向到主页
  if (to.path === "/login") {
    return next({ path: "/" })
  }

  // 如果用户已经获得其权限角色
  if (userStore.roles.length !== 0)  {
    return next()
  }
  // 否则要重新获取权限角色
  try {
    await userStore.getInfo()
    // 注意：角色必须是一个数组！ 例如: ["admin"] 或 ["developer", "editor"]
    const Layouts = () => import("@/layouts/index.vue")
    let modules = import.meta.glob('../views/**/*.vue')
    const roles = userStore.roles.filter((i:any)=>i.type == 1|| i.type == 2).map((item: any)=>{
        let roleItem = {
          path: `${item.url || ''}`,
          meta: {
            title: item.name,
            elIcon: item.icon,
            keepAlive :true
          },
          name:item.code,
          parentId:item.parentId,
          menuId:item.id,
          code: item.code
        }
        if(item.type == 2) {
          roleItem.component = modules[`../views${item.url}/index.vue`]
        } else {
          roleItem.component = Layouts
          roleItem.children= []
        }
        // console.log(roleItem)
        return roleItem
    })

    
    permissionStore.setRoutes(buildTree(roles))
    
    permissionStore.addRoutes.forEach((route) => {
      router.addRoute(route)
    })
    // console.log(permissionStore,'-----------------roles------------')
    next({ ...to, replace: true })
  } catch (err: any) {
    userStore.resetToken()
    ElMessage.error(err.message || "路由守卫过程发生错误")
    next("/login")
  }
})

router.afterEach((to) => {
  setRouteChange(to)
  setTitle(to.meta.title)
  NProgress.done()
})
